package com.stoneapple.timesheet.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.stoneapple.timesheet.entity.Profile;

public class ProfileDao {

	private static ProfileDao instance;

	private ProfileDao() {
	}

	public static ProfileDao getInstance() {
		if (instance == null) {
			instance = new ProfileDao();
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	public List<Profile> getProfileList() {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em.createQuery("SELECT * P FROM Profile P  ");
		List<Profile> profile = query.getResultList();
		return profile;
	}

	@SuppressWarnings("unchecked")
	public List<Profile> getProfileListByUserId(String userId) {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em
				.createQuery("SELECT P FROM Profile P WHERE author = :userId");
		query.setParameter("userId", userId);
		List<Profile> profile = query.getResultList();
		return profile;
	}

	public void save(String userId, String firstname, String lastname,
			String nickname, String position, String employeecode, String country) {
		synchronized (this) {
			EntityManager em = EMF.get().createEntityManager();
			Profile profile = new Profile(userId, firstname, lastname, nickname,
					position, employeecode, country);
			try {
				em.persist(profile);
			} finally {
				em.close();
			}
		}
	}

}
